package com.xue.action;

import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * 
 * @author 北京八维博大科技 薛建新
 * @date 2022年7月7日 下午2:35:03
 * @Copyright 北京八维博大科技
 */
public final class SslTool {

	private static KeyStore getKeyStore(String keyStorePath, String password, String type) throws Exception {

		InputStream is = SslTool.class.getResourceAsStream(keyStorePath);
		if (null == is) {
			System.out.println(keyStorePath+"找不到此文件!!!!");
		}
		KeyStore ks = KeyStore.getInstance(type);
		ks.load(is, password.toCharArray());

		return ks;
	}

	// 参考
	// https://vimsky.com/examples/detail/java-method-javax.net.ssl.KeyManagerFactory.getInstance.html
	// https://blog.csdn.net/HD243608836/article/details/118706090
	public static final SSLContext getSSLContext() throws Exception {
		// load up the key store
		// 客户端只需要公钥，或从浏览器下载公钥
		String PASS = "123456";
		
		
		
		// 初始化密钥库
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance("SunX509");
        KeyStore keyStore = getKeyStore("client1.pfx", PASS, "PKCS12");
        keyManagerFactory.init(keyStore, PASS.toCharArray());
        // 初始化信任库
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance("SunX509");
        KeyStore trustkeyStore = getKeyStore("client_trust.jks", PASS, "JKS");
        trustManagerFactory.init(trustkeyStore);
		
		
		
		
		
		

		// 获得密钥库
//		KeyStore ks = KeyStore.getInstance(STORETYPE);
//		InputStream is = SslTool.class.getResourceAsStream(fileName);
//		if (null == is) {
//			System.out.println("key store文件路径不正确!!!!");
//		}
//		ks.load(is, STOREPASSWORD.toCharArray());
//
//		// 实例化密钥库 Initialize the keymanager and trustmanager and add them to the SSL
//		// context
//		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());// getInstance("SunX509")
//		kmf.init(ks, KEYPASSWORD.toCharArray());
//		// 初始化信任库
//		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); // getInstance(TrustManagerFactory.getDefaultAlgorithm())
//																				// ;//
//		tmf.init(ks);

		SSLContext sslContext = SSLContext.getInstance("TLSv1.2");// TLSv1.2 或TLS
//		SSLContext sslContext = SSLContext.getInstance("TLS");//TLSv1.2 或TLS
		//sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
		
		
		sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory
                .getTrustManagers(), null);
//		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
		return sslContext;
	}
}
